package com.taptech.doufu.ui.view;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.taptech.doufu.R;
import com.taptech.doufu.app.WeMediaApplication;
import com.taptech.doufu.manager.UserLogManager;
import com.taptech.doufu.bean.GiftBean;
import com.taptech.doufu.bean.ProductionBean;
import com.taptech.doufu.listener.HttpResponseListener;
import com.taptech.doufu.services.personalcenter.AccountService;
import com.taptech.doufu.services.GiftService;
import com.taptech.doufu.util.DiaobaoUtil;
import com.taptech.doufu.util.ImageManager;
import com.taptech.doufu.util.SharedPreferenceUtil;
import com.taptech.doufu.util.TMAnalysis;
import com.taptech.doufu.util.UIUtil;
import com.taptech.doufu.net.httputils.HttpResponseObject;
import com.taptech.doufu.net.httputils.HttpUtil;
import com.taptech.doufu.weex.notification.QLXNotificationCenter;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

/**
 * Created by longsiyang on 16/1/8.
 */
public class GiftDialogManager implements View.OnClickListener, HttpResponseListener, GiftDisplayView.OnSelectListener , View.OnTouchListener {

    static Activity mContext;
    static GiftDialogManager giftManager;
    static View rootView;
    private static String mId, mObjectType;
    PopupWindow giftPopupWindow;

    static ProductionBean bean;

    List<GiftBean> mDataList;
    // 当前选择的第几个
    public int currentChoose = -1;
    public int currentChooseNum = 0;
    public int currentPagePos = 0;

    // 是否送过礼物
    boolean hasSendGift = false;

    // Dialog UI View
    ImageView backBtn;

    ViewStub waitDialog;
    TextView sendGiftBtn;
    TextView giftSendingSignTextView;
    RelativeLayout giftSendLayout;

    ViewPager giftViewPager;
    PagerAdapter adapter;
    List<GiftDisplayView> viewList;

    // top view
    ImageView topDefaultImg;
    RelativeLayout topChooseLayout;
    SimpleDraweeView topChooseImg;
    TextView giftNumTextView;
    ImageView giftMinuteBtn;
    TextView giftToUserName;
    TextView gift_notice;

    // pay dialog view
    RelativeLayout payDialogLayout;
    TextView payCancelBtn;
    TextView jumpToPayBtn;
    TextView payDesContentText;

    //rush
    private ImageView mRushGuideImage;
    private ViewStub mRushGuideLayout;
    private ImageView mGiftPageLeft;
    private ImageView mGiftPageRight;
    private View viewNight;


    // gift animation
    GiftAnimManager giftAnimManager;

    // listener
    OnCloseGiftDialogListener onCloseGiftDialogListener;

    static public GiftDialogManager getInstance(Context context, ProductionBean productionBean) {
        return getInstance(context,productionBean,false);
    }


    static public GiftDialogManager getInstance(Context context, ProductionBean productionBean,boolean isNight) {
        giftManager = new GiftDialogManager();
        mContext = (Activity) context;
        bean = productionBean;
        giftManager.mDataList = new ArrayList<>();
        giftManager.viewList = new ArrayList<>();
        giftManager.initView(isNight);
        String object_type;
        if (productionBean.getObject_type().equals("5") || productionBean.getObject_type().equals("18")) {//小说
            object_type = "18";
        }else {//漫画
            object_type = "45";
        }
        GiftService.getInstance().loadGiftList(giftManager, object_type);
        return giftManager;
    }

    /**
     * 打赏弹窗初始化
     */
    private void initView(boolean isNight) {
        rootView = LayoutInflater.from(mContext).inflate(R.layout.gift_dialog_layout, null);
        gift_notice = (TextView) rootView.findViewById(R.id.gift_notice);
        giftPopupWindow = new PopupWindow(rootView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        giftPopupWindow.setAnimationStyle(R.style.Animation_Bottom_Top);
        giftPopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        giftPopupWindow.setBackgroundDrawable(new BitmapDrawable());

        giftPopupWindow.setFocusable(true);
        giftPopupWindow.setOutsideTouchable(true);
        giftPopupWindow.showAtLocation(mContext.getWindow().getDecorView(), Gravity.BOTTOM | Gravity.CENTER, 0, 0);
        giftPopupWindow.update();
        if(WeMediaApplication.getInstance().isDayNightMode_Night){
            View view =  rootView.findViewById(R.id.gift_dialog_black_bg);
            view.setBackgroundColor(mContext.getResources().getColor(R.color.black));
            view.setAlpha(0.5f);
        }

        initDialogView(isNight);
        initTopView();
        initPayDialogView();
        giftAnimManager = new GiftAnimManager(mContext , rootView);
    }

    /**
     * 中心窗初始化
     */
    private void initDialogView(boolean isNight) {
        backBtn = (ImageView) rootView.findViewById(R.id.popu_cancel_bt);
        backBtn.setOnClickListener(this);
        TextView casetBtn=(TextView)rootView.findViewById(R.id.popu_sure_tv);
        casetBtn.setOnClickListener(this);
        waitDialog = (ViewStub) rootView.findViewById(R.id.wait_dialog_viewstub);
        waitDialog.inflate();
        sendGiftBtn = (TextView) rootView.findViewById(R.id.send_gift_btn);
        giftSendingSignTextView = (TextView) rootView.findViewById(R.id.gift_sending_sign);
        giftSendLayout = (RelativeLayout) rootView.findViewById(R.id.send_gift_layout);
        giftSendLayout.setOnClickListener(this);
        giftViewPager = (ViewPager) rootView.findViewById(R.id.gift_img_viewpager);
        giftToUserName = (TextView) rootView.findViewById(R.id.gift_to_username_textview);
        giftToUserName.setText(bean.getUser().getName());
        mRushGuideLayout = (ViewStub) rootView.findViewById(R.id.rush_stub_layout);
        mGiftPageLeft = (ImageView) rootView.findViewById(R.id.gifts_page_left);
        mGiftPageRight = (ImageView) rootView.findViewById(R.id.gifts_page_right);
        viewNight = rootView.findViewById(R.id.viewNight);
        if (isNight) {
            viewNight.setVisibility(View.VISIBLE);
        }else{
            viewNight.setVisibility(View.GONE);
        }
        mGiftPageLeft.setOnClickListener(this);
        mGiftPageRight.setOnClickListener(this);

    }

    /**
     * 顶部窗初始化
     */
    private void initTopView() {
        topDefaultImg = (ImageView) rootView.findViewById(R.id.top_default_img);
        topChooseLayout = (RelativeLayout) rootView.findViewById(R.id.top_choose_layout);
        topChooseImg = (SimpleDraweeView) rootView.findViewById(R.id.top_choose_img);
        giftNumTextView = (TextView) rootView.findViewById(R.id.gift_num_textview);
        giftMinuteBtn = (ImageView) rootView.findViewById(R.id.minute_gift_num_btn);
        giftMinuteBtn.setOnTouchListener(this);

    }

    /**
     * 缺钱弹窗初始化
     */
    private void initPayDialogView(){
        payDialogLayout = (RelativeLayout) rootView.findViewById(R.id.pay_dialog_layout);
        payCancelBtn = (TextView) rootView.findViewById(R.id.pay_cancel_btn);
        jumpToPayBtn = (TextView) rootView.findViewById(R.id.jump_to_pay_btn);
        payDesContentText = (TextView) rootView.findViewById(R.id.text_des_content);
        payDialogLayout.setOnClickListener(this);
        payCancelBtn.setOnClickListener(this);
        jumpToPayBtn.setOnClickListener(this);
    }


    @Override
    public void handleResponse(int handleType, HttpResponseObject response) {
        if (waitDialog != null) {
            waitDialog.setVisibility(View.GONE);
        }
        switch (handleType){
            case GiftService.HANDLE_LOAD_GIFT_LIST:
                HttpUtil.setOnHandleHttpResponListener(mContext, handleType, response, listener);
                break;
            case GiftService.HANDLE_GIVE_GIFT_REQUEST:
                String topText = "礼物已送出";
                if (response.getStatus()==0){
                    try {
                        topText = ((JSONObject) response.getData()).get("message").toString();
                        int coins =  ((JSONObject) response.getData()).getJSONObject("reward_record").getInt("coins");
                        HashMap resParam = new HashMap();
                        resParam.put("add",coins);
                        QLXNotificationCenter.getInstance().postNotify("TFUserSendGiftSuccess",resParam);
                        UserLogManager.addLog(UserLogManager.LOG_EVENT_NAME_NOVEL_REWARD,bean.getId());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    giftAnimManager.animStart(mDataList.get(currentChoose).getAnimation_image(),mDataList.get(currentChoose).getDesc(),mDataList.get(currentChoose).getId(),topText);
                }
                // 余额不足
                else if (response.getStatus() == 32){
                    if (!payDialogLayout.isShown()){
                        TMAnalysis.event(mContext , "to_pay_dialog");
                        payDialogLayout.setVisibility(View.VISIBLE);
                        payDesContentText.setText(response.getUser_msg());
                    }
                }else {
                    UIUtil.toastMessage(mContext , response.getUser_msg());
                }
                // 送礼请求完成，可以再次发起请求
                hasSendGift = true;
                giftSending(false);

                break;
        }

    }

    HttpUtil.HandleHttpResponListener listener = new HttpUtil.HandleHttpResponListener() {
        @Override
        public void handleRespon(int handleType, JSONObject data) {
            switch (handleType) {
                case GiftService.HANDLE_LOAD_GIFT_LIST:
                    try {
                        JSONArray giftJson = data.getJSONArray("gifts");
                        List<GiftBean> dataList = DiaobaoUtil.json2list(GiftBean.class, giftJson);
                        if (mDataList != null && viewList.size() == 0) {
                            if (dataList.get(5).getName().equals("催更符")) {
                                showRushStub();
                            }
                            mDataList.clear();
                            mDataList.addAll(dataList);
                            for (int i = 0; i < (mDataList.size() - 1) / 6 + 1; i++) {
                                GiftDisplayView view = new GiftDisplayView(mContext);
                                viewList.add(view);
                            }
                            if (viewList.size() > 1) {
                                mGiftPageRight.setVisibility(View.VISIBLE);
                            }else {
                                mGiftPageRight.setVisibility(View.GONE);
                            }
                            adapter = new PagerAdapter() {
                                @Override
                                public int getCount() {
                                    if (viewList != null) {
                                        return viewList.size();
                                    }
                                    return 0;
                                }

                                @Override
                                public boolean isViewFromObject(View view, Object object) {
                                    return (view == object);
                                }

                                @Override
                                public Object instantiateItem(ViewGroup container, int position) {
                                    container.addView(viewList.get(position));
                                    viewList.get(position).setContentInfo(mDataList.subList(position * 6, ((position * 6 + 6) < mDataList.size() ? (position * 6 + 6) : mDataList.size()))
                                            , position, GiftDialogManager.this);
                                    return viewList.get(position);
                                }

                                @Override
                                public void destroyItem(ViewGroup container, int position, Object object) {
                                    container.removeView(viewList.get(position));
                                }
                            };
                            giftViewPager.setAdapter(adapter);
                            giftViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                                @Override
                                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                                }

                                @Override
                                public void onPageSelected(int position) {
                                    viewList.get(position).refreshView();
                                    currentPagePos = position;
                                    if (position + 1 == viewList.size()) {
                                        mGiftPageLeft.setVisibility(View.VISIBLE);
                                        mGiftPageRight.setVisibility(View.GONE);
                                    }
                                    if (position == 0 ){
                                        mGiftPageLeft.setVisibility(View.GONE);
                                        if (viewList.size() > 1) {
                                            mGiftPageRight.setVisibility(View.VISIBLE);
                                        }else {
                                            mGiftPageRight.setVisibility(View.GONE);
                                        }
                                    }
                                }

                                @Override
                                public void onPageScrollStateChanged(int state) {

                                }
                            });
                            String note = data.getString("note");
                            if (!TextUtils.isEmpty(note)) {
                                gift_notice.setText(note);
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;

            }
        }
    };

    @Override
    public void onClick(View v) {
        if (payDialogLayout!=null&&!payDialogLayout.isShown()){
            switch (v.getId()) {
                case R.id.rush_guide_image:
                    mRushGuideLayout.setVisibility(View.GONE);
                    SharedPreferenceUtil.saveRushGuideImage(mContext);
                    break;
                case R.id.gifts_page_left:
                    giftViewPager.setCurrentItem(currentPagePos -1);
                    break;
                case R.id.gifts_page_right:
                    giftViewPager.setCurrentItem(currentPagePos + 1);
                    break;
                case R.id.popu_cancel_bt:
                    giftPopupWindow.dismiss();
                    if (onCloseGiftDialogListener != null && hasSendGift == true){
                        onCloseGiftDialogListener.onCloseGiftDialog();
                    }
                    break;
                case R.id.popu_sure_tv:
                    GiftService.enterGiftListActivity(mContext , bean);
                    break;
                case R.id.send_gift_layout:
                    if (AccountService.getInstance().isLogin() ) {
                        if (currentChoose >= 0){
                            giftSending(true);
                            if (bean.getObject_type().equals("5")) {
                                GiftService.getInstance().sendGiftRequest(this, bean.getId(), "18", mDataList.get(currentChoose).getId() , String.valueOf(currentChooseNum));
                            } else {
                                GiftService.getInstance().sendGiftRequest(this, bean.getId(), bean.getObject_type(), mDataList.get(currentChoose).getId() , String.valueOf(currentChooseNum));
                            }
                            Map keyMap = new HashMap();
                            keyMap.put("mid" , mDataList.get(currentChoose).getId());
                            keyMap.put("mpos" , currentChoose );
                            keyMap.put("mtype" , mDataList.get(currentChoose).getObject_type());
                            TMAnalysis.event(mContext, "give_gift");
                        }else {
                            UIUtil.toastMessage(mContext , "请先选择打赏礼物");
                        }


                    } else {
                        AccountService.getInstance().jumpToLogin();
                    }
                    break;
                case R.id.pay_cancel_btn:
                    if (payDialogLayout.isShown()){
                        payDialogLayout.setVisibility(View.GONE);
                    }
                    break;
                case R.id.jump_to_pay_btn:
                    TMAnalysis.event(mContext , "jump_to_pay");
                    GiftService.enterPayWebActivity(mContext);
                    break;
            }
        }else {
            switch (v.getId()) {
                case R.id.pay_cancel_btn:
                    if (payDialogLayout.isShown()){
                        payDialogLayout.setVisibility(View.GONE);
                    }
                    break;
                case R.id.jump_to_pay_btn:
                    GiftService.enterPayWebActivity(mContext);
                    break;
            }
        }

    }

    private void showRushStub() {
        if (SharedPreferenceUtil.getRushGuideImage(mContext)) {
            //not need show
        }else {
            View rushGuideview = mRushGuideLayout.inflate();
            mRushGuideImage = (ImageView) rushGuideview.findViewById(R.id.rush_guide_image);
            mRushGuideImage.setOnClickListener(this);
        }
    }



    public interface OnCloseGiftDialogListener{
        void onCloseGiftDialog();
    }

    public void setOnCloseGiftDialogListener(OnCloseGiftDialogListener listener){
        this.onCloseGiftDialogListener = listener;
    }


    @Override
    public void onSelectd(int position) {
        for (int i = 0; i < mDataList.size(); i++) {
            mDataList.get(i).setIsSelected(false);
        }
        mDataList.get(position).setIsSelected(true);
        // 计算数量 如果再点击已选中的，或之前没选中
        if (currentChoose == position || currentChoose < 0){
            currentChooseNum++;
        }else {
            currentChooseNum=1;
        }

        currentChoose = position;
        if (currentChoose >= 0){
            topChooseLayout.setVisibility(View.VISIBLE);
            ImageManager.loadImage(topChooseImg, mDataList.get(currentChoose).getImage(), 1.0f);

            setGiftNum();
        }


    }




    // 触摸持续时间
    int touchLastTime = 0;
    // 100ms 发一次 10次 算一秒 就算点击了
    final int TouchEqualClick = 10;
    float[] actionDownXY = new float[2];
    private Handler timeHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what >= 0){
                sendGiftBtn.setText("打赏中" );
                giftSendLayout.setBackgroundResource(R.drawable.biankuang_btn_unable);
                giftSendingSignTextView.setText(giftSendingSign[msg.what % giftSendingSign.length]);
                giftSendLayout.setClickable(false);
            }else {
                sendGiftBtn.setText("打赏");
                giftSendLayout.setBackgroundResource(R.drawable.btn_reward_topay);
                giftSendingSignTextView.setText("");
                giftSendLayout.setClickable(true);
            }
        }
    };
    Runnable timeRunable = new Runnable() {
        @Override
        public void run() {
            if (timeHandler != null){
                touchLastTime ++;
                // 判定为长按
                if (touchLastTime > TouchEqualClick) {
                    // 每次长按生效
                    if (currentChooseNum > 1){
                        currentChooseNum--;
                        setGiftNum();
                    }
                }
                timeHandler.postDelayed(this, 100);
            }
        }
    };

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:

                if (touchLastTime == 0){
                    timeHandler.postDelayed(timeRunable, 100);
                }
                actionDownXY[0] = event.getX();
                actionDownXY[1] = event.getY();
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                if (!isActionMove(actionDownXY[0] , actionDownXY[1] , event.getX() , event.getY())){
                    // 抬起手
                    if (currentChooseNum >= 1){
                        currentChooseNum--;
                        setGiftNum();
                    }
                }
                if (currentChoose >= 0){
                    Map keyMap = new HashMap();
                    keyMap.put("mid" , mDataList.get(currentChoose).getId());
                    keyMap.put("mpos" , currentChoose );
                    keyMap.put("mprice" , mDataList.get(currentChoose).getCoins());
                    TMAnalysis.event(mContext, "minute_item_gift");

                }

                touchLastTime = 0;
                if (timeHandler != null){
                    timeHandler.removeCallbacks(timeRunable);
                }
                break;
        }
        return true;
    }

    private boolean isActionMove(float oldX , float oldY , float x , float y){

        float distance = 20.0f;
        if (Math.abs(oldX - x) > distance){
            return true;
        }
        if (Math.abs(oldY - y) > distance){
            return true;
        }

        return false;
    }

    // 显示礼物数量
    private void setGiftNum(){
        if (currentChooseNum > 0){
            giftNumTextView.setText("×" + currentChooseNum+" ");
            giftNumTextView.setVisibility(View.VISIBLE);

        }else {
            giftNumTextView.setVisibility(View.GONE);

        }
        if (currentChooseNum >= 1){
            giftMinuteBtn.setVisibility(View.VISIBLE);
        }else {
            giftMinuteBtn.setVisibility(View.GONE);
            currentChoose = -1;
            currentChooseNum = 0;
            topDefaultImg.setVisibility(View.VISIBLE);
            topChooseLayout.setVisibility(View.GONE);
            for (int i = 0; i < mDataList.size(); i++) {
                mDataList.get(i).setIsSelected(false);
            }
            viewList.get(currentPagePos).refreshView();

        }
    }

    String[] giftSendingSign = new String[]{"." , ".." , "..."};
    int waitSecond = -1;
    Runnable giftSendingTimer = new Runnable() {
        @Override
        public void run() {
            waitSecond++;
            timeHandler.sendEmptyMessage(waitSecond);
            timeHandler.postDelayed(this , 700);

        }
    };

    private void giftSending(boolean isSending){
        if (isSending){
            timeHandler.postDelayed(giftSendingTimer, 0);

        }else {
            timeHandler.removeCallbacks(giftSendingTimer);
            sendGiftBtn.setText("打赏");
            giftSendLayout.setBackgroundResource(R.drawable.btn_reward_topay);
            giftSendingSignTextView.setText("");
            giftSendLayout.setClickable(true);
            waitSecond = -1;
        }
    }


}
